<template>
	<view class="main">
		<view class="up">
			<swiper class="swiper-container" :indicator-dots="true" indicator-color="rgba(255, 255, 255, 0.5)"
				:autoplay="true" :interval="3000" :duration="1000">
				<swiper-item v-for="(item, index) in imgList" :key="index">
					<image :src="item" class="swiper-image" mode="aspectFill" />
				</swiper-item>
			</swiper>
		</view>

		<view class="down">
			<view class="menu card-project shadow-project">
				<navigator url="../../subpages/news/news" open-type="navigate" class="item">
					<view class="item-inner">
						<view class="img shadow">
							<image src="../../static/images/notices.png" />
							<view class="badge" v-if="hasNewNotice">新</view>
						</view>
						<view class="title">本店公告</view>
					</view>
				</navigator>

				<navigator url="../../subpages/discountActivities/discountActivities" open-type="navigate" class="item">
					<view class="item-inner">
						<view class="img shadow">
							<image src="../../static/images/activities.png" />
							<view class="badge" v-if="hasNewActivity">新</view>
						</view>
						<view class="title">店内活动</view>
					</view>
				</navigator>

				<navigator open-type="navigate" url="../../subpages/exampleDemo/exampleDemo" class="item">
					<view class="item-inner">
						<view class="img shadow">
							<image src="../../static/images/exampleDemo.png" />
						</view>
						<view class="title">成功案例</view>
					</view>
				</navigator>

				<navigator open-type="navigate" url="../../subpages/aboutus/aboutus" class="item">
					<view class="item-inner">
						<view class="img shadow">
							<image src="../../static/images/aboutus.png" />
						</view>
						<view class="title">关于我们</view>
					</view>
				</navigator>

			</view>

			<!-- 添加推荐产品区域 -->
			<view class="recommend-section">
				<view class="section-title">
					<text class="title-text">推荐服务</text>
					<navigator url="/pages/products/products" open-type="switchTab" class="more-link">
						查看更多 >
					</navigator>
				</view>

				<view class="product-grid">
					<view class="product-item" v-for="(item, index) in recommendProducts" :key="index"
						@tap="goToDetail(item)">
						<view class="product-tag">推荐</view>
						<image :src="item.image" mode="aspectFill" class="product-image"></image>
						<view class="product-info">
							<text class="product-title">{{item.title}}</text>
							<view class="price-section">
								<text class="product-price">¥{{item.price}}</text>
								<text class="sale-count">已售{{item.sold}}件</text>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 添加可拖动的客服按钮 -->
		<view class="float-customer-service" :style="{ left: serviceBtn.left + 'px', top: serviceBtn.top + 'px' }"
			@touchstart="touchStart" @touchmove="touchMove" @touchend="touchEnd" @tap="contactService">
			<image src="/static/images/services.png" mode="aspectFit" class="service-icon"></image>
			<text class="service-text">客服咨询</text>
		</view>
	</view>
</template>

<script>
import config from '@/config/config.js'

export default {
	data() {
		return {
			imgList: [],
			recommendProducts: [],
			serviceBtn: {
				left: uni.getSystemInfoSync().windowWidth - 80,
				top: uni.getSystemInfoSync().windowHeight - 140,
				startX: 0,
				startY: 0,
				moveX: 0,
				moveY: 0,
			},
			hasNewNotice: false,
			hasNewActivity: false
		}
	},
	methods: {
		goToDetail(item) {
			uni.navigateTo({
				url: `/subpages/productDetail/productDetail?id=${item.id}`
			})
		},
		touchStart(e) {
			this.serviceBtn.startX = e.touches[0].clientX
			this.serviceBtn.startY = e.touches[0].clientY
			this.serviceBtn.moveX = this.serviceBtn.left
			this.serviceBtn.moveY = this.serviceBtn.top
		},
		touchMove(e) {
			let moveX = e.touches[0].clientX - this.serviceBtn.startX
			let moveY = e.touches[0].clientY - this.serviceBtn.startY

			// 计算新位置
			let newLeft = this.serviceBtn.moveX + moveX
			let newTop = this.serviceBtn.moveY + moveY

			// 获取屏幕尺寸
			const systemInfo = uni.getSystemInfoSync()
			const maxWidth = systemInfo.windowWidth - 70 // 考虑按钮宽度
			const maxHeight = systemInfo.windowHeight - 70 // 考虑按钮高度

			// 限制拖动范围
			newLeft = Math.min(Math.max(10, newLeft), maxWidth)
			newTop = Math.min(Math.max(10, newTop), maxHeight)

			this.serviceBtn.left = newLeft
			this.serviceBtn.top = newTop
		},
		touchEnd() {
			// 可以添加吸附效果
			const systemInfo = uni.getSystemInfoSync()
			const halfWidth = systemInfo.windowWidth / 2

			// 自动吸附到左右两侧
			if (this.serviceBtn.left < halfWidth) {
				this.serviceBtn.left = 10
			} else {
				this.serviceBtn.left = systemInfo.windowWidth - 70
			}
		},
		contactService() {
			// 跳转到客服页面或打开客服会话
			uni.navigateTo({
				url: '/subpages/custoemrService/custoemrService'
			})
		},
		//初始化轮播图
		async initSwaperImgs() {
			try {
				// 先从缓存中获取系统配置
				const cachedConfig = uni.getStorageSync('slSysConfig')
				
				if (cachedConfig) {
					console.log('从缓存获取系统配置:', cachedConfig)
					// 如果有缓存数据，直接使用
					this.imgList = cachedConfig.swiperIndexList || []
					return
				}
				
				// 如果没有缓存，调用接口获取
				const result = await this.$http.post(config.api.slconfig.getConfig)
				console.log('系统配置响应:', result)
				
				if (result.data.code === 200 || result.data.code == 201) {
					const configData = result.data.data
					
					// 存入缓存
					uni.setStorageSync('slSysConfig', configData)
					
					// 更新轮播图列表
					this.imgList = configData.swiperIndexList || []
				} else {
					throw new Error(result.data.msg || '获取系统配置失败')
				}
			} catch (err) {
				console.error('获取系统配置失败:', err)
				uni.showToast({
					title: err.message || '获取系统配置失败',
					icon: 'none'
				})
			}
		},
		// 获取推荐产品列表
		async initIndex() {
			try {
				uni.showLoading({
					title: '加载中...'
				})
				const result = await this.$http.post(config.api.slconfig.initIndex)
				console.log('首页初始化:', result)
				
				if (result.data.code === 200 || result.data.code === 201) {
					const data = result.data.data
					
					// 设置推荐产品
					const products = data.slProducts || []
					this.recommendProducts = products.map(item => ({
						id: item.id,
						image: item.productImg,
						title: item.productName,
						price: item.productPrice,
						sold: item.saleNum || 0
					}))
					
					// 检查新活动
					if (data.latestActivityId) {
						const savedActivityId = uni.getStorageSync('savedActivityId')
						console.log('活动ID对比:', {
							latest: data.latestActivityId,
							saved: savedActivityId
						})
						this.hasNewActivity = !savedActivityId || savedActivityId !== data.latestActivityId
					} else {
						this.hasNewActivity = false
					}
					
					// 检查新公告
					if (data.latestNoticeId) {
						const savedNoticeId = uni.getStorageSync('savedNoticeId')
						console.log('公告ID对比:', {
							latest: data.latestNoticeId,
							saved: savedNoticeId
						})
						this.hasNewNotice = !savedNoticeId || savedNoticeId !== data.latestNoticeId
					} else {
						this.hasNewNotice = false
					}
				}
			} catch (err) {
				console.error('初始化失败:', err)
				uni.showToast({
					title: err.message || '初始化失败',
					icon: 'none'
				})
			} finally {
				uni.hideLoading()
			}
		},
		async onPullDownRefresh() {
			try {
				// 重新加载数据
				await Promise.all([
					this.initSwaperImgs(),
					this.initIndex()
				])
			} catch (err) {
				console.error('刷新失败:', err)
			} finally {
				// 停止下拉刷新动画
				uni.stopPullDownRefresh()
			}
		}
	},
	onLoad() {
		//初始化轮播图
		this.initSwaperImgs()
		// 在页面加载时获取推荐产品
		this.initIndex()
		// 设置导航栏样式
		uni.setNavigationBarColor({
			frontColor: '#ffffff',
			backgroundColor: '#000000'
		})
	},
	onShow() {
		// 每次页面显示时重新获取数据
		this.initIndex()
	}
}
</script>

<style lang="scss">
	@import "../../stytle/comm_box.css";
	@import "../../stytle/skin.css";

	.main {
		padding: 0 0 30rpx;
	}

	.swiper-container {
		width: 100%;
		height: 300px;
		/* 根据实际需求调整轮播图的高度 */
	}

	.swiper-image {
		width: 100%;
		height: 100%;
	}

	.down {
		width: 100%;
		box-sizing: border-box;
		padding: 20rpx;
		z-index: 9999;
	}

	.menu {
		display: flex;
		background-color: #fff;
		padding: 20rpx 10rpx;
		border-radius: 20rpx;
	}

	.menu .item {
		width: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		height: 180rpx;

	}

	.menu .item .item-inner {
		width: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;

	}

	.menu .item-inner .img {
		width: 105rpx;
		height: 105rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		background-color: #7a7776;
		border-radius: 25rpx;
		position: relative;
	}

	.menu .item-inner .img image {
		width: 75rpx;
		height: 75rpx;
	}

	.menu .item-inner .title {
		margin-top: 20rpx;
		font-size: 26rpx;
		color: #4f5368;
	}

	.home-list-box {
		width: 100%;
		margin-bottom: 200rpx;
		margin-top: 20rpx;
	}

	.home-list-box .comm-list-box {
		padding: 20rpx 0rpx 30rpx 0rpx;
		overflow: unset;
	}

	.comm-list-box .item-leftbig1 .leftbig-left {
		border-radius: 10rpx !important;
		border-top-right-radius: 30rpx !important;
		border-bottom-left-radius: 30rpx !important;
	}

	/* 添加推荐产品样式 */
	.recommend-section {
		margin-top: 30rpx;
		background: #fff;
		border-radius: 20rpx;
		padding: 20rpx;
	}

	.section-title {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx 10rpx;
		border-bottom: 1rpx solid #f5f5f5;
	}

	.title-text {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}

	.more-link {
		font-size: 24rpx;
		color: #999;
	}

	.product-grid {
		display: grid;
		grid-template-columns: repeat(2, 1fr);
		gap: 20rpx;
		padding: 20rpx 0;
	}

	.product-item {
		position: relative;
		background: #fff;
		border-radius: 12rpx;
		overflow: hidden;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
	}

	.product-tag {
		position: absolute;
		top: 16rpx;
		right: 16rpx;
		background: #ff4757;
		color: #fff;
		font-size: 22rpx;
		padding: 4rpx 12rpx;
		border-radius: 20rpx;
		z-index: 1;
	}

	.product-image {
		width: 100%;
		height: 200rpx;
		background-color: #f5f5f5;
	}

	.product-info {
		padding: 16rpx;
	}

	.product-title {
		font-size: 26rpx;
		color: #333;
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 2;
		overflow: hidden;
		line-height: 1.4;
	}

	.price-section {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-top: 12rpx;
	}

	.product-price {
		font-size: 32rpx;
		color: #ff4757;
		font-weight: bold;
	}

	.sale-count {
		font-size: 22rpx;
		color: #999;
	}

	/* 添加客服按钮样式 */
	.float-customer-service {
		position: fixed;
		z-index: 999;
		display: flex;
		flex-direction: column;
		align-items: center;
		background: rgba(0, 0, 0, 0.7);
		backdrop-filter: blur(5px);
		padding: 12rpx;
		border-radius: 16rpx;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.2);
		transition: transform 0.2s;
	}

	.float-customer-service:active {
		transform: scale(0.95);
	}

	.service-icon {
		width: 80rpx;
		height: 80rpx;
		margin-bottom: 6rpx;
	}

	.service-text {
		font-size: 20rpx;
		color: #ffffff;
		line-height: 1;
	}

	/* 添加新消息标志样式 */
	.img {
		position: relative;
		
		.badge {
			position: absolute;
			top: -8rpx;
			right: -8rpx;
			background-color: #ff4757;
			color: #fff;
			font-size: 20rpx;
			padding: 4rpx 12rpx;
			border-radius: 20rpx;
			z-index: 1;
		}
	}
</style>